export default {
  mounted(el) {
    let isDragging = false;
    let startX = 0;
    let startY = 0;
    let initialX = 0;
    let initialY = 0;

    // 确保元素可定位
    const style = window.getComputedStyle(el);
    if (!['fixed', 'absolute'].includes(style.position)) {
      el.style.position = 'fixed';
    }

    // 初始化位置
    const rect = el.getBoundingClientRect();
    initialX = rect.left;
    initialY = rect.top;
    el.style.left = `${initialX}px`;
    el.style.top = `${initialY}px`;

    // 阻止默认触摸滚动
    el.style.touchAction = 'none';

    function handleTouchStart(e) {
      if (e.touches.length !== 1) return;
      const touch = e.touches[0];
      startX = touch.clientX;
      startY = touch.clientY;
      const currentRect = el.getBoundingClientRect();
      initialX = currentRect.left;
      initialY = currentRect.top;
      el.classList.add('dragging');
      document.addEventListener('touchmove', handleTouchMove);
      document.addEventListener('touchend', handleTouchEnd);
      document.addEventListener('touchcancel', handleTouchEnd);
    }

    function handleTouchMove(e) {
      if (e.touches.length !== 1) return;
      const touch = e.touches[0];
      const deltaX = touch.clientX - startX;
      const deltaY = touch.clientY - startY;

      // 判断是否开始拖拽
      if (!isDragging && (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5)) {
        isDragging = true;
      }

      if (isDragging) {
        const newX = initialX + deltaX;
        const newY = initialY + deltaY;
        // 限制在视口范围内
        const maxX = window.innerWidth - el.offsetWidth;
        const maxY = window.innerHeight - el.offsetHeight;
        el.style.left = `${Math.max(0, Math.min(newX, maxX))}px`;
        el.style.top = `${Math.max(0, Math.min(newY, maxY))}px`;
        e.preventDefault();
      }
    }

    function handleTouchEnd(e) {
      document.removeEventListener('touchmove', handleTouchMove);
      document.removeEventListener('touchend', handleTouchEnd);
      document.removeEventListener('touchcancel', handleTouchEnd);
      el.classList.remove('dragging');
      if (isDragging) {
        e.preventDefault();
        isDragging = false;
      }
    }

    el.addEventListener('touchstart', handleTouchStart);

    // 保存处理函数以便卸载
    el._dragButtonHandlers = {
      handleTouchStart,
      handleTouchMove,
      handleTouchEnd
    };
  },
  beforeUnmount(el) {
    if (el._dragButtonHandlers) {
      const { handleTouchStart, handleTouchMove, handleTouchEnd } = el._dragButtonHandlers;
      el.removeEventListener('touchstart', handleTouchStart);
      document.removeEventListener('touchmove', handleTouchMove);
      document.removeEventListener('touchend', handleTouchEnd);
      document.removeEventListener('touchcancel', handleTouchEnd);
      delete el._dragButtonHandlers;
    }
  }

}
 